What is resolve?
The resolve npm package is a module for resolving file paths within a project. It is particularly useful for resolving the path of a module as Node.js would, taking into account node_modules folders and the package.json file. It can be used both programmatically and as a command-line tool.
What are resolve's main functionalities?
Asynchronously resolve the path of a module
This feature allows you to asynchronously find the path of a module from a given base directory. The callback receives the resolved path or an error if the module cannot be found.
const resolve = require('resolve');
resolve('module_name', { basedir: '/some/path' }, function (err, res) {
if (err) console.error(err);
else console.log(res);
});
Synchronously resolve the path of a module
This feature allows you to synchronously find the path of a module from a given base directory. It either returns the resolved path or throws an error if the module cannot be found.
const resolve = require('resolve');
try {
const res = resolve.sync('module_name', { basedir: '/some/path' });
console.log(res);
} catch (err) {
console.error(err);
}
Resolve a module with custom package filter
This feature allows you to specify a custom filter function to modify the package data before the resolution process. This can be useful for redirecting the main entry point of a package.
const resolve = require('resolve');
const opts = {
packageFilter: function (pkg) {
if (pkg.main) {
pkg.main = 'some-other-file.js';
}
return pkg;
}
};
resolve('module_name', opts, function (err, res) {
if (err) console.error(err);
else console.log(res);
});
Command-line interface
The resolve package also provides a command-line interface (CLI) that can be used to resolve the path of a module from the command line.
$ resolve module_name --basedir=/some/path
Other packages similar to resolve
enhanced-resolve
enhanced-resolve is a library that offers more advanced resolution options and plugins, similar to webpack's resolver. It is more complex and configurable compared to resolve.
browser-resolve
browser-resolve is a resolve algorithm that takes browser field in package.json into account. It is similar to resolve but is specifically designed for browser environments.
require-resolve
require-resolve is a package that mimics node's require.resolve function. It is similar to resolve but focuses on mimicking the behavior of Node.js's native require.resolve method.
resolve
implements the node require.resolve()
algorithm such that you can require.resolve()
on behalf of a file asynchronously and synchronously
example
asynchronously resolve:
var resolve = require('resolve/async');
resolve('tap', { basedir: __dirname }, function (err, res) {
if (err) console.error(err);
else console.log(res);
});
$ node example/async.js
/home/substack/projects/node-resolve/node_modules/tap/lib/main.js
synchronously resolve:
var resolve = require('resolve/sync');
var res = resolve('tap', { basedir: __dirname });
console.log(res);
$ node example/sync.js
/home/substack/projects/node-resolve/node_modules/tap/lib/main.js
methods
var resolve = require('resolve');
var async = require('resolve/async');
var sync = require('resolve/sync');
For both the synchronous and asynchronous methods, errors may have any of the following err.code
values:
MODULE_NOT_FOUND
: the given path string (id
) could not be resolved to a moduleINVALID_BASEDIR
: the specified opts.basedir
doesn't exist, or is not a directoryINVALID_PACKAGE_MAIN
: a package.json
was encountered with an invalid main
property (eg. not a string)
resolve(id, opts={}, cb)
Asynchronously resolve the module path string id
into cb(err, res [, pkg])
, where pkg
(if defined) is the data from package.json
.
options are:
-
opts.basedir - directory to begin resolving from
-
opts.package - package.json
data applicable to the module being loaded
-
opts.extensions - array of file extensions to search in order
-
opts.includeCoreModules - set to false
to exclude node core modules (e.g. fs
) from the search
-
opts.readFile - how to read files asynchronously
-
opts.isFile - function to asynchronously test whether a file exists
-
opts.isDirectory - function to asynchronously test whether a file exists and is a directory
-
opts.realpath - function to asynchronously resolve a potential symlink to its real path
-
opts.readPackage(readFile, pkgfile, cb)
- function to asynchronously read and parse a package.json file
- readFile - the passed
opts.readFile
or fs.readFile
if not specified - pkgfile - path to package.json
- cb - callback
-
opts.packageFilter(pkg, pkgfile, dir)
- transform the parsed package.json contents before looking at the "main" field
- pkg - package data
- pkgfile - path to package.json
- dir - directory that contains package.json
-
opts.pathFilter(pkg, path, relativePath)
- transform a path within a package
- pkg - package data
- path - the path being resolved
- relativePath - the path relative from the package.json location
- returns - a relative path that will be joined from the package.json location
-
opts.paths - require.paths array to use if nothing is found on the normal node_modules
recursive walk (probably don't use this)
For advanced users, paths
can also be a opts.paths(request, start, opts)
function
- request - the import specifier being resolved
- start - lookup path
- getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard
node_modules
resolution - opts - the resolution options
-
opts.packageIterator(request, start, opts)
- return the list of candidate paths where the packages sources may be found (probably don't use this)
- request - the import specifier being resolved
- start - lookup path
- getPackageCandidates - a thunk (no-argument function) that returns the paths using standard
node_modules
resolution - opts - the resolution options
-
opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: "node_modules"
-
opts.preserveSymlinks - if true, doesn't resolve basedir
to real path before resolving.
This is the way Node resolves dependencies when executed with the --preserve-symlinks flag.
Note: this property is currently true
by default but it will be changed to
false
in the next major version because Node's resolution algorithm does not preserve symlinks by default.
default opts
values:
{
paths: [],
basedir: __dirname,
extensions: ['.js'],
includeCoreModules: true,
readFile: fs.readFile,
isFile: function isFile(file, cb) {
fs.stat(file, function (err, stat) {
if (!err) {
return cb(null, stat.isFile() || stat.isFIFO());
}
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
return cb(err);
});
},
isDirectory: function isDirectory(dir, cb) {
fs.stat(dir, function (err, stat) {
if (!err) {
return cb(null, stat.isDirectory());
}
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
return cb(err);
});
},
realpath: function realpath(file, cb) {
var realpath = typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath;
realpath(file, function (realPathErr, realPath) {
if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);
else cb(null, realPathErr ? file : realPath);
});
},
readPackage: function defaultReadPackage(readFile, pkgfile, cb) {
readFile(pkgfile, function (readFileErr, body) {
if (readFileErr) cb(readFileErr);
else {
try {
var pkg = JSON.parse(body);
cb(null, pkg);
} catch (jsonErr) {
cb(null);
}
}
});
},
moduleDirectory: 'node_modules',
preserveSymlinks: true
}
resolve.sync(id, opts)
Synchronously resolve the module path string id
, returning the result and
throwing an error when id
can't be resolved.
options are:
-
opts.basedir - directory to begin resolving from
-
opts.extensions - array of file extensions to search in order
-
opts.includeCoreModules - set to false
to exclude node core modules (e.g. fs
) from the search
-
opts.readFileSync - how to read files synchronously
-
opts.isFile - function to synchronously test whether a file exists
-
opts.isDirectory - function to synchronously test whether a file exists and is a directory
-
opts.realpathSync - function to synchronously resolve a potential symlink to its real path
-
opts.readPackageSync(readFileSync, pkgfile)
- function to synchronously read and parse a package.json file
- readFileSync - the passed
opts.readFileSync
or fs.readFileSync
if not specified - pkgfile - path to package.json
-
opts.packageFilter(pkg, dir)
- transform the parsed package.json contents before looking at the "main" field
- pkg - package data
- dir - directory that contains package.json (Note: the second argument will change to "pkgfile" in v2)
-
opts.pathFilter(pkg, path, relativePath)
- transform a path within a package
- pkg - package data
- path - the path being resolved
- relativePath - the path relative from the package.json location
- returns - a relative path that will be joined from the package.json location
-
opts.paths - require.paths array to use if nothing is found on the normal node_modules
recursive walk (probably don't use this)
For advanced users, paths
can also be a opts.paths(request, start, opts)
function
- request - the import specifier being resolved
- start - lookup path
- getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard
node_modules
resolution - opts - the resolution options
-
opts.packageIterator(request, start, opts)
- return the list of candidate paths where the packages sources may be found (probably don't use this)
- request - the import specifier being resolved
- start - lookup path
- getPackageCandidates - a thunk (no-argument function) that returns the paths using standard
node_modules
resolution - opts - the resolution options
-
opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: "node_modules"
-
opts.preserveSymlinks - if true, doesn't resolve basedir
to real path before resolving.
This is the way Node resolves dependencies when executed with the --preserve-symlinks flag.
Note: this property is currently true
by default but it will be changed to
false
in the next major version because Node's resolution algorithm does not preserve symlinks by default.
default opts
values:
{
paths: [],
basedir: __dirname,
extensions: ['.js'],
includeCoreModules: true,
readFileSync: fs.readFileSync,
isFile: function isFile(file) {
try {
var stat = fs.statSync(file);
} catch (e) {
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
throw e;
}
return stat.isFile() || stat.isFIFO();
},
isDirectory: function isDirectory(dir) {
try {
var stat = fs.statSync(dir);
} catch (e) {
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
throw e;
}
return stat.isDirectory();
},
realpathSync: function realpathSync(file) {
try {
var realpath = typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync;
return realpath(file);
} catch (realPathErr) {
if (realPathErr.code !== 'ENOENT') {
throw realPathErr;
}
}
return file;
},
readPackageSync: function defaultReadPackageSync(readFileSync, pkgfile) {
var body = readFileSync(pkgfile);
try {
var pkg = JSON.parse(body);
return pkg;
} catch (jsonErr) {}
},
moduleDirectory: 'node_modules',
preserveSymlinks: true
}
install
With npm do:
npm install resolve
license
MIT